﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommonEntity.CommonImageEntities;
using FellowOakDicom;
using ImageDomain.Utils;

namespace ImageDomain.DE;
public class SplitDicomsDE : ISplitDicomsDE
{
    public Dictionary<string, SplitSeriesInfo> SplitSeriesDic { get; private set; }
    public SplitSeriesInfo CurrentSelectedSeries { get; private set; }

    public async Task BuildSeriesDic(string dir)
    {
        SplitSeriesDic = new Dictionary<string, SplitSeriesInfo>();
        await Task.Run(() =>
        {
            var dcms = DcmHelper.GetAllDicomFiles(dir);
            if (dcms?.Count == 0) return;

            foreach (var dcm in dcms)
            {
                var rs = GetSequence(dcm);
                var key = $"{rs[0]}-{rs[5]}-{rs[4]}";
                if (!SplitSeriesDic.Keys.Contains(key.Trim()))
                {
                    SplitSeriesDic[key] = new SplitSeriesInfo()
                    {
                        PatientName = rs[0],
                        PatientId = rs[1],
                        StudyUid = rs[2],
                        StudyDescription = rs[3],
                        SeriesDescription = rs[4],
                        SeriesTime = rs[5],
                        Height = Convert.ToInt32(rs[6]),
                        Width = Convert.ToInt32(rs[7]),
                        Dicoms = new List<string>()
                    };
                }

                SplitSeriesDic[key].Dicoms.Add(dcm);
            }

        });
    }

    public void SelectSeries(string key)
    {
        if (!SplitSeriesDic.Keys.Contains(key)) throw new Exception("未发现此序列");
        CurrentSelectedSeries = SplitSeriesDic[key];
    }


    private IList<string>? GetSequence(string filepath)
    {
        try
        {
            var dicomFile = DicomFile.Open(filepath);
            var dataset = dicomFile.Dataset;

            var patientName = dataset.GetString(DicomTag.PatientName);
            var patientId = dataset.GetString(DicomTag.PatientID);

            var studyUid = dataset.GetString(DicomTag.StudyID);
            var studyDescription = dataset.GetString(DicomTag.StudyDescription);

            var seriesDescription = dataset.GetString(DicomTag.SeriesDescription);
            var seriesTime = dataset.GetString(DicomTag.SeriesTime);

            var rows = dataset.GetString(DicomTag.Rows);
            var cols = dataset.GetString(DicomTag.Columns);

            //return $"{patientName}-{seriesTime}-{seriesDescription}";

            var rs = new List<string>() { patientName, patientId, studyUid, studyDescription, seriesDescription, seriesTime, rows, cols };
            return rs;
        }
        catch (Exception)
        {
            return null;
        }
    }

}
